<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP数学服务器 - 在线计算器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .main-content {
            padding: 40px;
        }

        .tabs {
            display: flex;
            border-bottom: 2px solid #f0f0f0;
            margin-bottom: 30px;
        }

        .tab {
            padding: 15px 30px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 16px;
            color: #666;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .tab.active {
            color: #4facfe;
            border-bottom-color: #4facfe;
            font-weight: 600;
        }

        .tab:hover {
            color: #4facfe;
            background: #f8f9ff;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .calc-section {
            background: #f8f9ff;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 20px;
        }

        .calc-section h3 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.3em;
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }

        .input-group input, .input-group select, .input-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .input-group input:focus, .input-group select:focus, .input-group textarea:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.3);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .btn-small {
            padding: 8px 16px;
            font-size: 14px;
        }

        .result {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            min-height: 60px;
            font-family: 'Courier New', monospace;
        }

        .result.success {
            border-color: #4caf50;
            background: #f1f8e9;
        }

        .result.error {
            border-color: #f44336;
            background: #ffebee;
            color: #c62828;
        }

        .matrix-input {
            display: grid;
            gap: 10px;
            margin-bottom: 20px;
        }

        .matrix-row {
            display: flex;
            gap: 10px;
        }

        .matrix-cell {
            width: 80px;
            padding: 8px;
            text-align: center;
        }

        .vector-input {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4facfe;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .examples {
            background: #fff3e0;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
        }

        .examples h4 {
            color: #e65100;
            margin-bottom: 10px;
        }

        .examples ul {
            list-style-type: none;
            padding-left: 0;
        }

        .examples li {
            padding: 5px 0;
            color: #666;
        }

        .examples code {
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
        }

        .sub-tabs {
            display: flex;
            margin-bottom: 20px;
            background: #f0f0f0;
            border-radius: 8px;
            padding: 4px;
        }

        .sub-tab {
            flex: 1;
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 14px;
            color: #666;
            transition: all 0.3s ease;
            border-radius: 6px;
        }

        .sub-tab.active {
            background: white;
            color: #4facfe;
            font-weight: 600;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .sub-content {
            display: none;
        }

        .sub-content.active {
            display: block;
        }

        .matrix-size-input {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 20px;
            background: #f0f4f8;
            padding: 15px;
            border-radius: 10px;
            border: 2px solid #e1e8ed;
        }

        .matrix-size-input label {
            color: #37474f;
            font-weight: 600;
            margin: 0;
        }

        .matrix-size-input input {
            width: 80px;
            padding: 8px 12px;
            border: 2px solid #cfd8dc;
            border-radius: 6px;
            text-align: center;
            font-weight: 600;
            background: white;
        }

        .matrix-size-input input:focus {
            border-color: #4facfe;
            box-shadow: 0 0 0 2px rgba(79, 172, 254, 0.1);
        }

        .matrix-size-input span {
            color: #546e7a;
            font-weight: 600;
            font-size: 18px;
        }

        .auto-detect {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
            border: 1px solid #4caf50;
        }

        .quick-input {
            margin-bottom: 20px;
            background: #f8f9ff;
            padding: 20px;
            border-radius: 12px;
            border: 2px solid #e3f2fd;
            transition: all 0.3s ease;
        }

        .quick-input:hover {
            border-color: #4facfe;
            box-shadow: 0 4px 12px rgba(79, 172, 254, 0.1);
        }

        .quick-input label {
            color: #1976d2;
            font-weight: 600;
            margin-bottom: 12px;
            display: block;
        }

        .quick-input textarea {
            height: 100px;
            font-family: 'Courier New', monospace;
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            font-size: 14px;
            line-height: 1.5;
            resize: vertical;
            transition: all 0.3s ease;
        }

        .quick-input textarea:focus {
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
            outline: none;
        }

        .quick-input textarea::placeholder {
            color: #999;
            font-style: italic;
        }

        .quick-input-buttons {
            display: flex;
            gap: 10px;
            margin-top: 12px;
        }

        .error-message {
            background: #ffebee;
            color: #c62828;
            padding: 10px 15px;
            border-radius: 6px;
            border-left: 4px solid #f44336;
            margin-top: 10px;
            font-size: 14px;
            display: none;
        }

        .success-message {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 10px 15px;
            border-radius: 6px;
            border-left: 4px solid #4caf50;
            margin-top: 10px;
            font-size: 14px;
            display: none;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🧮 MCP数学服务器</h1>
            <p>强大的在线数学计算工具 - 支持基本运算、表达式计算和线性代数</p>
        </div>

        <div class="main-content">
            <div class="tabs">
                <button class="tab active" onclick="showTab('calculator')">数学计算器</button>
                <button class="tab" onclick="showTab('linear')">线性代数</button>
            </div>

            <!-- 数学计算器 -->
            <div id="calculator" class="tab-content active">
                <div class="calc-section">
                    <h3>📝 数学表达式计算</h3>
                    <div class="input-group">
                        <label for="expr-input">输入数学表达式:</label>
                        <input type="text" id="expr-input" placeholder="例如: (2 + 3) * 4 - 5 ** 2">
                    </div>
                    <button class="btn" onclick="calculateExpression()">🚀 计算表达式</button>
                    <button class="btn btn-secondary" onclick="clearExpression()">🗑️ 清空</button>
                    
                    <div class="examples">
                        <h4>💡 支持的运算符:</h4>
                        <ul>
                            <li>加法: <code>+</code> | 减法: <code>-</code> | 乘法: <code>*</code> | 除法: <code>/</code></li>
                            <li>乘方: <code>**</code> | 括号: <code>( )</code> | 根号: <code>sqrt()</code></li>
                        </ul>
                        <h4>📋 示例:</h4>
                        <ul>
                            <li>基本运算: <code>10 + 5</code>, <code>15 / 3</code>, <code>2 ** 3</code>, <code>sqrt(16)</code></li>
                            <li>复杂表达式: <code>(2 + 3) * 4</code>, <code>2 ** 3 + 5</code>, <code>sqrt(25) + 10</code></li>
                        </ul>
                    </div>
                </div>
                <div id="calculator-result" class="result">计算结果将在这里显示...</div>
            </div>

            <!-- 线性代数 -->
            <div id="linear" class="tab-content">
                <div class="calc-section">
                    <h3>🔬 线性代数运算</h3>
                    
                    <!-- 子主题选择 -->
                    <div class="sub-tabs">
                        <button class="sub-tab active" onclick="showSubTab('equation-solving')">求解方程组</button>
                        <button class="sub-tab" onclick="showSubTab('eigenvalue')">特征值计算</button>
                    </div>

                    <!-- 求解方程组子主题 -->
                    <div id="equation-solving" class="sub-content active">
                        <div class="input-group">
                            <label for="equation-method">选择求解方法:</label>
                            <select id="equation-method" onchange="updateEquationInputs()">
                                <option value="gaussian_elimination">高斯消元法</option>
                                <option value="lu_decomposition">LU分解法</option>
                                <option value="qr_decomposition">QR分解法</option>
                            </select>
                        </div>
                        
                        <!-- 矩阵维度设置 -->
                         <div class="matrix-size-input">
                             <label>矩阵维度:</label>
                             <input type="number" id="equation-matrix-rows" value="3" min="2" max="10" onchange="generateEquationMatrixInputs()" readonly>
                             <span>×</span>
                             <input type="number" id="equation-matrix-cols" value="3" min="2" max="10" onchange="generateEquationMatrixInputs()" readonly>
                             <span class="auto-detect">自动检测</span>
                         </div>
                        
                        <!-- 快捷输入 -->
                         <div class="quick-input">
                             <label>🚀 智能矩阵输入 (自动识别维度)</label>
                             <textarea id="equation-quick-matrix" placeholder="支持多种格式：\n• [1,2,3;4,5,6;7,8,9]\n• 【1，2，3；4，5，6；7，8，9】\n• [[1,2,3],[4,5,6],[7,8,9]]\n• 1 2 3\n  4 5 6\n  7 8 9"></textarea>
                             <div class="quick-input-buttons">
                                 <button class="btn btn-small" onclick="parseQuickMatrix('equation')">🔍 解析矩阵</button>
                                 <button class="btn btn-small btn-secondary" onclick="clearQuickInput('equation', 'matrix')">🗑️ 清空</button>
                             </div>
                             <div id="equation-matrix-error" class="error-message"></div>
                             <div id="equation-matrix-success" class="success-message"></div>
                         </div>
                        
                        <div class="input-group">
                            <label>系数矩阵 A:</label>
                            <div id="equation-matrix-inputs"></div>
                        </div>
                        
                        <div class="quick-input">
                             <label>🎯 智能向量输入</label>
                             <textarea id="equation-quick-vector" placeholder="支持多种格式：\n• [1,2,3]\n• 【1，2，3】\n• 1,2,3\n• 1 2 3"></textarea>
                             <div class="quick-input-buttons">
                                 <button class="btn btn-small" onclick="parseQuickVector('equation')">🔍 解析向量</button>
                                 <button class="btn btn-small btn-secondary" onclick="clearQuickInput('equation', 'vector')">🗑️ 清空</button>
                             </div>
                             <div id="equation-vector-error" class="error-message"></div>
                             <div id="equation-vector-success" class="success-message"></div>
                         </div>
                        
                        <div class="input-group">
                            <label>常数向量 b:</label>
                            <div id="equation-vector-inputs"></div>
                        </div>
                        
                        <!-- LU和QR分解的可选项 -->
                        <div id="decomposition-options" style="display: none;">
                            <div class="checkbox-group">
                                <input type="checkbox" id="show-decomposition" checked>
                                <label for="show-decomposition">显示分解过程</label>
                            </div>
                        </div>
                        
                        <button class="btn" onclick="calculateEquation()">🚀 求解方程组</button>
                        <button class="btn btn-secondary" onclick="clearEquation()">🗑️ 清空</button>
                        <button class="btn btn-secondary" onclick="loadEquationExample()">📋 加载示例</button>
                    </div>

                    <!-- 特征值计算子主题 -->
                    <div id="eigenvalue" class="sub-content">
                        <div class="input-group">
                            <label for="eigenvalue-method">选择计算方法:</label>
                            <select id="eigenvalue-method" onchange="updateEigenvalueInputs()">
                                <option value="power_method">幂法（主特征值）</option>
                                <option value="jacobi_method">雅可比方法（所有特征值）</option>
                            </select>
                        </div>
                        
                        <!-- 矩阵维度设置 -->
                         <div class="matrix-size-input">
                             <label>矩阵维度:</label>
                             <input type="number" id="eigenvalue-matrix-size" value="3" min="2" max="10" onchange="generateEigenvalueMatrixInputs()" readonly>
                             <span>×</span>
                             <input type="number" id="eigenvalue-matrix-size-copy" value="3" min="2" max="10" readonly>
                             <span class="auto-detect">自动检测</span>
                         </div>
                        
                        <!-- 快捷输入 -->
                         <div class="quick-input">
                             <label>🚀 智能矩阵输入 (自动识别维度)</label>
                             <textarea id="eigenvalue-quick-matrix" placeholder="支持多种格式：\n• [4,3,2;3,4,1;2,1,3]\n• 【4，3，2；3，4，1；2，1，3】\n• [[4,3,2],[3,4,1],[2,1,3]]\n• 4 3 2\n  3 4 1\n  2 1 3"></textarea>
                             <div class="quick-input-buttons">
                                 <button class="btn btn-small" onclick="parseQuickMatrix('eigenvalue')">🔍 解析矩阵</button>
                                 <button class="btn btn-small btn-secondary" onclick="clearQuickInput('eigenvalue', 'matrix')">🗑️ 清空</button>
                             </div>
                             <div id="eigenvalue-matrix-error" class="error-message"></div>
                             <div id="eigenvalue-matrix-success" class="success-message"></div>
                         </div>
                        
                        <div class="input-group">
                            <label>系数矩阵 A:</label>
                            <div id="eigenvalue-matrix-inputs"></div>
                        </div>
                        
                        <button class="btn" onclick="calculateEigenvalue()">🚀 计算特征值</button>
                        <button class="btn btn-secondary" onclick="clearEigenvalue()">🗑️ 清空</button>
                        <button class="btn btn-secondary" onclick="loadEigenvalueExample()">📋 加载示例</button>
                    </div>
                    
                    <div class="examples">
                        <h4>💡 功能说明:</h4>
                        <ul>
                            <li><strong>高斯消元法:</strong> 经典的线性方程组求解方法</li>
                            <li><strong>LU分解法:</strong> 将矩阵分解为下三角矩阵L和上三角矩阵U，然后求解</li>
                            <li><strong>QR分解法:</strong> 将矩阵分解为正交矩阵Q和上三角矩阵R，然后求解</li>
                            <li><strong>幂法:</strong> 计算矩阵的主特征值和对应特征向量</li>
                            <li><strong>雅可比方法:</strong> 计算对称矩阵的所有特征值和特征向量</li>
                        </ul>
                        <h4>📋 快捷输入格式:</h4>
                        <ul>
                            <li>矩阵: <code>[1,2,3;4,5,6;7,8,9]</code> (分号分隔行，逗号分隔列)</li>
                            <li>向量: <code>[1,2,3]</code> (逗号分隔元素)</li>
                        </ul>
                    </div>
                </div>
                <div id="linear-result" class="result">线性代数计算结果将在这里显示...</div>
            </div>
        </div>
    </div>

    <div class="loading" id="loading">
        <div class="spinner"></div>
        <p>正在计算中，请稍候...</p>
    </div>

    <script>
        // 标签页切换
        function showTab(tabName) {
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));
            
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
        }

        // 子标签页切换
        function showSubTab(subTabName) {
            const contents = document.querySelectorAll('.sub-content');
            contents.forEach(content => content.classList.remove('active'));
            
            const tabs = document.querySelectorAll('.sub-tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            
            document.getElementById(subTabName).classList.add('active');
            event.target.classList.add('active');
        }

        // 表达式计算
        function calculateExpression() {
            const expression = document.getElementById('expr-input').value;
            
            if (!expression.trim()) {
                showResult('calculator-result', '请输入数学表达式', false);
                return;
            }
            
            showLoading(true);
            
            fetch('/api/expression', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({expression: expression})
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.success) {
                    showResult('calculator-result', `${expression} = ${data.result}`, true);
                } else {
                    showResult('calculator-result', `错误: ${data.error}`, false);
                }
            })
            .catch(error => {
                showLoading(false);
                showResult('calculator-result', `网络错误: ${error.message}`, false);
            });
        }

        function clearExpression() {
            document.getElementById('expr-input').value = '';
            document.getElementById('calculator-result').innerHTML = '计算结果将在这里显示...';
            document.getElementById('calculator-result').className = 'result';
        }

        // 求解方程组相关函数
        function updateEquationInputs() {
            const method = document.getElementById('equation-method').value;
            const options = document.getElementById('decomposition-options');
            
            if (method === 'lu_decomposition' || method === 'qr_decomposition') {
                options.style.display = 'block';
            } else {
                options.style.display = 'none';
            }
        }

        function generateEquationMatrixInputs() {
            const rows = parseInt(document.getElementById('equation-matrix-rows').value);
            const cols = parseInt(document.getElementById('equation-matrix-cols').value);
            
            // 生成矩阵输入
            const matrixContainer = document.getElementById('equation-matrix-inputs');
            matrixContainer.innerHTML = '';
            const matrixDiv = document.createElement('div');
            matrixDiv.className = 'matrix-input';
            
            for (let i = 0; i < rows; i++) {
                const rowDiv = document.createElement('div');
                rowDiv.className = 'matrix-row';
                for (let j = 0; j < cols; j++) {
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.step = 'any';
                    input.className = 'matrix-cell';
                    input.id = `equation-matrix-${i}-${j}`;
                    input.placeholder = `a${i+1}${j+1}`;
                    rowDiv.appendChild(input);
                }
                matrixDiv.appendChild(rowDiv);
            }
            matrixContainer.appendChild(matrixDiv);
            
            // 生成向量输入
            const vectorContainer = document.getElementById('equation-vector-inputs');
            vectorContainer.innerHTML = '';
            const vectorDiv = document.createElement('div');
            vectorDiv.className = 'vector-input';
            
            for (let i = 0; i < rows; i++) {
                const input = document.createElement('input');
                input.type = 'number';
                input.step = 'any';
                input.className = 'matrix-cell';
                input.id = `equation-vector-${i}`;
                input.placeholder = `b${i+1}`;
                vectorDiv.appendChild(input);
            }
            vectorContainer.appendChild(vectorDiv);
        }

        function parseQuickMatrix(type) {
            const quickInput = document.getElementById(`${type}-quick-matrix`).value.trim();
            if (!quickInput) return;
            
            try {
                // 解析格式如 [1,2,3;4,5,6;7,8,9]
                const matrixStr = quickInput.replace(/\[|\]/g, '');
                const rows = matrixStr.split(';');
                const matrix = rows.map(row => row.split(',').map(val => parseFloat(val.trim())));
                
                if (type === 'equation') {
                    document.getElementById('equation-matrix-rows').value = matrix.length;
                    document.getElementById('equation-matrix-cols').value = matrix[0].length;
                    generateEquationMatrixInputs();
                    
                    // 填充矩阵值
                    for (let i = 0; i < matrix.length; i++) {
                        for (let j = 0; j < matrix[i].length; j++) {
                            const element = document.getElementById(`equation-matrix-${i}-${j}`);
                            if (element) element.value = matrix[i][j];
                        }
                    }
                } else if (type === 'eigenvalue') {
                    document.getElementById('eigenvalue-matrix-size').value = matrix.length;
                    generateEigenvalueMatrixInputs();
                    
                    // 填充矩阵值
                    for (let i = 0; i < matrix.length; i++) {
                        for (let j = 0; j < matrix[i].length; j++) {
                            const element = document.getElementById(`eigenvalue-matrix-${i}-${j}`);
                            if (element) element.value = matrix[i][j];
                        }
                    }
                }
            } catch (error) {
                alert('矩阵格式错误，请使用格式: [1,2,3;4,5,6;7,8,9]');
            }
        }

        function parseQuickVector(type) {
            const quickInput = document.getElementById(`${type}-quick-vector`).value.trim();
            if (!quickInput) return;
            
            try {
                // 解析格式如 [1,2,3]
                const vectorStr = quickInput.replace(/\[|\]/g, '');
                const vector = vectorStr.split(',').map(val => parseFloat(val.trim()));
                
                if (type === 'equation') {
                    // 填充向量值
                    for (let i = 0; i < vector.length; i++) {
                        const element = document.getElementById(`equation-vector-${i}`);
                        if (element) element.value = vector[i];
                    }
                }
            } catch (error) {
                alert('向量格式错误，请使用格式: [1,2,3]');
            }
        }

        function calculateEquation() {
            const method = document.getElementById('equation-method').value;
            const rows = parseInt(document.getElementById('equation-matrix-rows').value);
            const cols = parseInt(document.getElementById('equation-matrix-cols').value);
            
            // 获取矩阵数据
            const matrix = [];
            for (let i = 0; i < rows; i++) {
                const row = [];
                for (let j = 0; j < cols; j++) {
                    const value = document.getElementById(`equation-matrix-${i}-${j}`).value;
                    if (!value) {
                        showResult('linear-result', `请填写矩阵元素 a${i+1}${j+1}`, false);
                        return;
                    }
                    row.push(parseFloat(value));
                }
                matrix.push(row);
            }
            
            // 获取向量数据
            const vector = [];
            for (let i = 0; i < rows; i++) {
                const value = document.getElementById(`equation-vector-${i}`).value;
                if (!value) {
                    showResult('linear-result', `请填写向量元素 b${i+1}`, false);
                    return;
                }
                vector.push(parseFloat(value));
            }
            
            let data = {
                operation: method,
                matrix: matrix,
                vector: vector
            };
            
            // 对于LU和QR分解，添加求解方程组标志
            if (method === 'lu_decomposition' || method === 'qr_decomposition') {
                data.solve_system = true;
            }
            
            showLoading(true);
            
            fetch('/api/linear_algebra', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.success) {
                    displayEquationResult(data.result, method);
                } else {
                    showResult('linear-result', `错误: ${data.error}`, false);
                }
            })
            .catch(error => {
                showLoading(false);
                showResult('linear-result', `网络错误: ${error.message}`, false);
            });
        }

        function displayEquationResult(result, method) {
            let displayText = '';
            
            if (method === 'gaussian_elimination') {
                // 高斯消元法结果
                if (Array.isArray(result)) {
                    displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">方程组的解:</div>';
                    result.forEach((value, index) => {
                        displayText += `<div style="background: #e8f5e8; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #4caf50;">`;
                        displayText += `<span style="font-weight: bold;">x<sub>${index + 1}</sub></span> = <span style="color: #1976d2; font-family: monospace; font-size: 1.1em;">${value.toFixed(6)}</span>`;
                        displayText += `</div>`;
                    });
                }
            } else if (method === 'lu_decomposition' || method === 'qr_decomposition') {
                // LU或QR分解结果
                if (result.solve_system) {
                    // 显示方程组解
                    displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">方程组的解:</div>';
                    result.solution.forEach((value, index) => {
                        displayText += `<div style="background: #e8f5e8; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #4caf50;">`;
                        displayText += `<span style="font-weight: bold;">x<sub>${index + 1}</sub></span> = <span style="color: #1976d2; font-family: monospace; font-size: 1.1em;">${value.toFixed(6)}</span>`;
                        displayText += `</div>`;
                    });
                    
                    // 如果选择显示分解过程
                    if (document.getElementById('show-decomposition').checked) {
                        displayText += '<hr style="margin: 20px 0;">';
                        displayText += displayDecompositionResult(result.decomposition, method);
                    }
                } else {
                    displayText = displayDecompositionResult(result, method);
                }
            }
            
            const element = document.getElementById('linear-result');
            element.innerHTML = displayText;
            element.className = 'result success';
        }

        function displayDecompositionResult(result, method) {
            let displayText = '';
            
            if (method === 'lu_decomposition') {
                displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">LU分解结果:</div>';
                
                // 显示L矩阵
                displayText += '<div style="font-weight: bold; margin: 15px 0 10px 0; color: #1976d2;">下三角矩阵 L:</div>';
                displayText += '<div style="background: #e3f2fd; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #2196f3;">';
                displayText += '<table style="border-collapse: collapse; margin: 0 auto; font-family: monospace;">';
                result.L_matrix.forEach((row, i) => {
                    displayText += '<tr>';
                    row.forEach((val, j) => {
                        displayText += `<td style="padding: 8px 12px; text-align: center; border: 1px solid #ddd; background: ${i >= j ? '#f8f9fa' : '#fff'};">${val.toFixed(6)}</td>`;
                    });
                    displayText += '</tr>';
                });
                displayText += '</table></div>';
                
                // 显示U矩阵
                displayText += '<div style="font-weight: bold; margin: 15px 0 10px 0; color: #1976d2;">上三角矩阵 U:</div>';
                displayText += '<div style="background: #e8f5e8; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #4caf50;">';
                displayText += '<table style="border-collapse: collapse; margin: 0 auto; font-family: monospace;">';
                result.U_matrix.forEach((row, i) => {
                    displayText += '<tr>';
                    row.forEach((val, j) => {
                        displayText += `<td style="padding: 8px 12px; text-align: center; border: 1px solid #ddd; background: ${i <= j ? '#f8f9fa' : '#fff'};">${val.toFixed(6)}</td>`;
                    });
                    displayText += '</tr>';
                });
                displayText += '</table></div>';
            } else if (method === 'qr_decomposition') {
                displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">QR分解结果:</div>';
                
                // 显示Q矩阵
                displayText += '<div style="font-weight: bold; margin: 15px 0 10px 0; color: #1976d2;">正交矩阵 Q:</div>';
                displayText += '<div style="background: #e3f2fd; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #2196f3;">';
                displayText += '<table style="border-collapse: collapse; margin: 0 auto; font-family: monospace;">';
                result.Q_matrix.forEach(row => {
                    displayText += '<tr>';
                    row.forEach(val => {
                        displayText += `<td style="padding: 8px 12px; text-align: center; border: 1px solid #ddd; background: #f8f9fa;">${val.toFixed(6)}</td>`;
                    });
                    displayText += '</tr>';
                });
                displayText += '</table></div>';
                
                // 显示R矩阵
                displayText += '<div style="font-weight: bold; margin: 15px 0 10px 0; color: #1976d2;">上三角矩阵 R:</div>';
                displayText += '<div style="background: #e8f5e8; padding: 15px; margin: 10px 0; border-radius: 8px; border-left: 4px solid #4caf50;">';
                displayText += '<table style="border-collapse: collapse; margin: 0 auto; font-family: monospace;">';
                result.R_matrix.forEach((row, i) => {
                    displayText += '<tr>';
                    row.forEach((val, j) => {
                        displayText += `<td style="padding: 8px 12px; text-align: center; border: 1px solid #ddd; background: ${i <= j ? '#f8f9fa' : '#fff'};">${val.toFixed(6)}</td>`;
                    });
                    displayText += '</tr>';
                });
                displayText += '</table></div>';
            }
            
            return displayText;
        }

        function clearEquation() {
            const rows = parseInt(document.getElementById('equation-matrix-rows').value);
            const cols = parseInt(document.getElementById('equation-matrix-cols').value);
            
            // 清空矩阵
            for (let i = 0; i < rows; i++) {
                for (let j = 0; j < cols; j++) {
                    const element = document.getElementById(`equation-matrix-${i}-${j}`);
                    if (element) element.value = '';
                }
            }
            
            // 清空向量
            for (let i = 0; i < rows; i++) {
                const element = document.getElementById(`equation-vector-${i}`);
                if (element) element.value = '';
            }
            
            // 清空快捷输入
            document.getElementById('equation-quick-matrix').value = '';
            document.getElementById('equation-quick-vector').value = '';
            
            document.getElementById('linear-result').innerHTML = '线性代数计算结果将在这里显示...';
            document.getElementById('linear-result').className = 'result';
        }

        function loadEquationExample() {
            const method = document.getElementById('equation-method').value;
            
            if (method === 'gaussian_elimination') {
                // 加载示例: 2x + 3y + 4z = 9, 3x + 4y + 2z = 9, 4x + 2y + 5z = 11
                document.getElementById('equation-matrix-rows').value = '3';
                document.getElementById('equation-matrix-cols').value = '3';
                generateEquationMatrixInputs();
                
                const exampleMatrix = [[2, 3, 4], [3, 4, 2], [4, 2, 5]];
                const exampleVector = [9, 9, 11];
                
                for (let i = 0; i < 3; i++) {
                    for (let j = 0; j < 3; j++) {
                        document.getElementById(`equation-matrix-${i}-${j}`).value = exampleMatrix[i][j];
                    }
                    document.getElementById(`equation-vector-${i}`).value = exampleVector[i];
                }
            } else {
                // LU和QR分解的示例矩阵
                document.getElementById('equation-matrix-rows').value = '3';
                document.getElementById('equation-matrix-cols').value = '3';
                generateEquationMatrixInputs();
                
                const exampleMatrix = [[4, 3, 2], [3, 4, 1], [2, 1, 3]];
                const exampleVector = [13, 12, 8];
                
                for (let i = 0; i < 3; i++) {
                    for (let j = 0; j < 3; j++) {
                        document.getElementById(`equation-matrix-${i}-${j}`).value = exampleMatrix[i][j];
                    }
                    document.getElementById(`equation-vector-${i}`).value = exampleVector[i];
                }
            }
        }

        // 特征值计算相关函数
        function updateEigenvalueInputs() {
            // 特征值计算不需要特殊处理
        }

        function generateEigenvalueMatrixInputs() {
            const size = parseInt(document.getElementById('eigenvalue-matrix-size').value);
            
            // 生成矩阵输入
            const matrixContainer = document.getElementById('eigenvalue-matrix-inputs');
            matrixContainer.innerHTML = '';
            const matrixDiv = document.createElement('div');
            matrixDiv.className = 'matrix-input';
            
            for (let i = 0; i < size; i++) {
                const rowDiv = document.createElement('div');
                rowDiv.className = 'matrix-row';
                for (let j = 0; j < size; j++) {
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.step = 'any';
                    input.className = 'matrix-cell';
                    input.id = `eigenvalue-matrix-${i}-${j}`;
                    input.placeholder = `a${i+1}${j+1}`;
                    rowDiv.appendChild(input);
                }
                matrixDiv.appendChild(rowDiv);
            }
            matrixContainer.appendChild(matrixDiv);
        }

        function calculateEigenvalue() {
            const method = document.getElementById('eigenvalue-method').value;
            const size = parseInt(document.getElementById('eigenvalue-matrix-size').value);
            
            // 获取矩阵数据
            const matrix = [];
            for (let i = 0; i < size; i++) {
                const row = [];
                for (let j = 0; j < size; j++) {
                    const value = document.getElementById(`eigenvalue-matrix-${i}-${j}`).value;
                    if (!value) {
                        showResult('linear-result', `请填写矩阵元素 a${i+1}${j+1}`, false);
                        return;
                    }
                    row.push(parseFloat(value));
                }
                matrix.push(row);
            }
            
            let data = {
                operation: method,
                matrix: matrix
            };
            
            showLoading(true);
            
            fetch('/api/linear_algebra', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                if (data.success) {
                    displayEigenvalueResult(data.result, method);
                } else {
                    showResult('linear-result', `错误: ${data.error}`, false);
                }
            })
            .catch(error => {
                showLoading(false);
                showResult('linear-result', `网络错误: ${error.message}`, false);
            });
        }

        function displayEigenvalueResult(result, method) {
            let displayText = '';
            
            if (typeof result === 'string') {
                try {
                    result = JSON.parse(result);
                } catch (e) {
                    // 如果不是JSON，直接显示
                }
            }
            
            if (method === 'power_method') {
                displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">幂法计算结果:</div>';
                displayText += `<div style="background: #e3f2fd; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #2196f3;">`;
                displayText += `<span style="font-weight: bold;">主特征值:</span> <span style="color: #1976d2; font-family: monospace; font-size: 1.1em;">${result.eigenvalue.toFixed(6)}</span>`;
                displayText += `</div>`;
                displayText += `<div style="background: #e8f5e8; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #4caf50;">`;
                displayText += `<span style="font-weight: bold;">对应特征向量:</span> [${result.eigenvector.map(x => x.toFixed(6)).join(', ')}]`;
                displayText += `</div>`;
                displayText += `<div style="background: #fff3e0; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #ff9800;">`;
                displayText += `<span style="font-weight: bold;">迭代次数:</span> ${result.iterations} | <span style="font-weight: bold;">验证误差:</span> ${result.verification_error.toFixed(8)}`;
                displayText += `</div>`;
            } else if (method === 'jacobi_method') {
                displayText = '<div style="font-weight: bold; margin-bottom: 15px; color: #2e7d32;">雅可比方法计算结果:</div>';
                displayText += '<div style="font-weight: bold; margin-bottom: 10px; color: #1976d2;">特征值:</div>';
                result.eigenvalues.forEach((value, index) => {
                    displayText += `<div style="background: #e3f2fd; padding: 8px; margin: 3px 0; border-radius: 5px; border-left: 4px solid #2196f3;">`;
                    displayText += `λ<sub>${index + 1}</sub> = <span style="color: #1976d2; font-family: monospace; font-size: 1.1em;">${value.toFixed(6)}</span>`;
                    displayText += `</div>`;
                });
                displayText += '<div style="font-weight: bold; margin: 15px 0 10px 0; color: #1976d2;">对应特征向量:</div>';
                result.eigenvectors.forEach((vector, index) => {
                    displayText += `<div style="background: #e8f5e8; padding: 8px; margin: 3px 0; border-radius: 5px; border-left: 4px solid #4caf50;">`;
                    displayText += `v<sub>${index + 1}</sub> = [${vector.map(x => x.toFixed(6)).join(', ')}]`;
                    displayText += `</div>`;
                });
                displayText += `<div style="background: #fff3e0; padding: 10px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #ff9800;">`;
                displayText += `<span style="font-weight: bold;">迭代次数:</span> ${result.iterations} | <span style="font-weight: bold;">验证误差:</span> ${result.verification_error.toFixed(8)}`;
                displayText += `</div>`;
            }
            
            const element = document.getElementById('linear-result');
            element.innerHTML = displayText;
            element.className = 'result success';
        }

        function clearEigenvalue() {
            const size = parseInt(document.getElementById('eigenvalue-matrix-size').value);
            
            // 清空矩阵
            for (let i = 0; i < size; i++) {
                for (let j = 0; j < size; j++) {
                    const element = document.getElementById(`eigenvalue-matrix-${i}-${j}`);
                    if (element) element.value = '';
                }
            }
            
            // 清空快捷输入
            document.getElementById('eigenvalue-quick-matrix').value = '';
            
            document.getElementById('linear-result').innerHTML = '线性代数计算结果将在这里显示...';
            document.getElementById('linear-result').className = 'result';
        }

        function loadEigenvalueExample() {
            const method = document.getElementById('eigenvalue-method').value;
            
            document.getElementById('eigenvalue-matrix-size').value = '3';
            generateEigenvalueMatrixInputs();
            
            const exampleMatrix = [[4, 3, 2], [3, 4, 1], [2, 1, 3]];
            for (let i = 0; i < 3; i++) {
                for (let j = 0; j < 3; j++) {
                    document.getElementById(`eigenvalue-matrix-${i}-${j}`).value = exampleMatrix[i][j];
                }
            }
        }

        // 智能输入解析函数
        function normalizeInput(input) {
            // 将全角字符转换为半角字符
            return input
                .replace(/，/g, ',')        // 全角逗号
                .replace(/；/g, ';')        // 全角分号
                .replace(/【/g, '[')        // 全角左方括号
                .replace(/】/g, ']')        // 全角右方括号
                .replace(/（/g, '(')        // 全角左圆括号
                .replace(/）/g, ')')        // 全角右圆括号
                .replace(/０/g, '0')        // 全角数字
                .replace(/１/g, '1')
                .replace(/２/g, '2')
                .replace(/３/g, '3')
                .replace(/４/g, '4')
                .replace(/５/g, '5')
                .replace(/６/g, '6')
                .replace(/７/g, '7')
                .replace(/８/g, '8')
                .replace(/９/g, '9')
                .replace(/．/g, '.')        // 全角小数点
                .replace(/－/g, '-');       // 全角减号
        }

        function showMessage(type, category, message, isError = false) {
            const errorElement = document.getElementById(`${type}-${category}-error`);
            const successElement = document.getElementById(`${type}-${category}-success`);
            
            if (isError) {
                errorElement.textContent = message;
                errorElement.style.display = 'block';
                successElement.style.display = 'none';
            } else {
                successElement.textContent = message;
                successElement.style.display = 'block';
                errorElement.style.display = 'none';
            }
            
            // 3秒后自动隐藏消息
            setTimeout(() => {
                errorElement.style.display = 'none';
                successElement.style.display = 'none';
            }, 3000);
        }

        function clearQuickInput(type, category) {
            const input = document.getElementById(`${type}-quick-${category}`);
            if (input) {
                input.value = '';
                showMessage(type, category, '输入已清空', false);
            }
        }

        function parseQuickMatrix(type) {
            const quickInput = document.getElementById(`${type}-quick-matrix`);
            let input = quickInput.value.trim();
            
            if (!input) {
                showMessage(type, 'matrix', '请输入矩阵数据', true);
                return;
            }
            
            try {
                // 标准化输入
                input = normalizeInput(input);
                
                let matrix;
                
                // 支持多种格式解析
                if (input.startsWith('[') && input.endsWith(']')) {
                    // 格式1: [1,2,3;4,5,6;7,8,9]
                    const content = input.slice(1, -1);
                    const rows = content.split(';');
                    matrix = rows.map(row => {
                        const values = row.split(',').map(val => {
                            const num = parseFloat(val.trim());
                            if (isNaN(num)) throw new Error(`无效数字: ${val.trim()}`);
                            return num;
                        });
                        return values;
                    });
                } else if (input.includes('[[') && input.includes(']]')) {
                    // 格式2: [[1,2,3],[4,5,6],[7,8,9]]
                    try {
                        matrix = JSON.parse(input);
                        if (!Array.isArray(matrix) || !Array.isArray(matrix[0])) {
                            throw new Error('格式错误');
                        }
                    } catch {
                        throw new Error('JSON格式解析失败');
                    }
                } else {
                    // 格式3: 多行文本格式
                    const rows = input.split('\n').filter(row => row.trim());
                    if (rows.length === 0) throw new Error('未找到有效行');
                    
                    matrix = rows.map(row => {
                        const values = row.trim().split(/[\s,]+/).map(val => {
                            const num = parseFloat(val.trim());
                            if (isNaN(num)) throw new Error(`无效数字: ${val.trim()}`);
                            return num;
                        });
                        return values;
                    });
                }
                
                // 验证矩阵
                if (!matrix || matrix.length === 0) {
                    throw new Error('矩阵为空');
                }
                
                const rows = matrix.length;
                const cols = matrix[0].length;
                
                if (cols === 0) {
                    throw new Error('矩阵列数为0');
                }
                
                // 验证所有行的列数一致
                for (let i = 0; i < rows; i++) {
                    if (matrix[i].length !== cols) {
                        throw new Error(`第${i+1}行有${matrix[i].length}列，期望${cols}列`);
                    }
                }
                
                // 验证维度限制
                if (rows < 2 || rows > 10 || cols < 2 || cols > 10) {
                    throw new Error(`矩阵维度必须在2x2到10x10之间，当前为${rows}x${cols}`);
                }
                
                // 对于特征值计算，必须是方阵
                if (type === 'eigenvalue' && rows !== cols) {
                    throw new Error(`特征值计算需要方阵，当前为${rows}x${cols}`);
                }
                
                // 更新维度并生成输入框
                if (type === 'equation') {
                    document.getElementById('equation-matrix-rows').value = rows;
                    document.getElementById('equation-matrix-cols').value = cols;
                    generateEquationMatrixInputs();
                    
                    // 填充矩阵
                    for (let i = 0; i < rows; i++) {
                        for (let j = 0; j < cols; j++) {
                            const input = document.getElementById(`equation-matrix-${i}-${j}`);
                            if (input) input.value = matrix[i][j];
                        }
                    }
                } else if (type === 'eigenvalue') {
                    document.getElementById('eigenvalue-matrix-size').value = rows;
                    document.getElementById('eigenvalue-matrix-size-copy').value = rows;
                    generateEigenvalueMatrixInputs();
                    
                    // 填充矩阵
                    for (let i = 0; i < rows; i++) {
                        for (let j = 0; j < cols; j++) {
                            const input = document.getElementById(`eigenvalue-matrix-${i}-${j}`);
                            if (input) input.value = matrix[i][j];
                        }
                    }
                }
                
                showMessage(type, 'matrix', `✅ 成功解析${rows}x${cols}矩阵`, false);
                
            } catch (error) {
                showMessage(type, 'matrix', `❌ ${error.message}`, true);
            }
        }

        function parseQuickVector(type) {
            const quickInput = document.getElementById(`${type}-quick-vector`);
            let input = quickInput.value.trim();
            
            if (!input) {
                showMessage(type, 'vector', '请输入向量数据', true);
                return;
            }
            
            try {
                // 标准化输入
                input = normalizeInput(input);
                
                let vector;
                
                if (input.startsWith('[') && input.endsWith(']')) {
                    // 格式: [1,2,3]
                    const content = input.slice(1, -1);
                    vector = content.split(',').map(val => {
                        const num = parseFloat(val.trim());
                        if (isNaN(num)) throw new Error(`无效数字: ${val.trim()}`);
                        return num;
                    });
                } else {
                    // 格式: 1,2,3 或 1 2 3
                    vector = input.split(/[\s,]+/).filter(val => val.trim()).map(val => {
                        const num = parseFloat(val.trim());
                        if (isNaN(num)) throw new Error(`无效数字: ${val.trim()}`);
                        return num;
                    });
                }
                
                // 验证向量
                if (vector.length === 0) {
                    throw new Error('向量为空');
                }
                
                if (vector.length > 10) {
                    throw new Error(`向量长度不能超过10，当前为${vector.length}`);
                }
                
                // 检查是否与矩阵维度匹配
                if (type === 'equation') {
                    const matrixRows = parseInt(document.getElementById('equation-matrix-rows').value);
                    if (vector.length !== matrixRows) {
                        throw new Error(`向量长度(${vector.length})与矩阵行数(${matrixRows})不匹配`);
                    }
                }
                
                // 填充向量
                for (let i = 0; i < vector.length; i++) {
                    const input = document.getElementById(`${type}-vector-${i}`);
                    if (input) input.value = vector[i];
                }
                
                showMessage(type, 'vector', `✅ 成功解析长度为${vector.length}的向量`, false);
                
            } catch (error) {
                showMessage(type, 'vector', `❌ ${error.message}`, true);
            }
        }

        // 工具函数
        function showResult(elementId, message, isSuccess) {
            const element = document.getElementById(elementId);
            const messageStr = typeof message === 'string' ? message : String(message);
            element.innerHTML = messageStr.replace(/\n/g, '<br>');
            element.className = isSuccess ? 'result success' : 'result error';
        }

        function showLoading(show) {
            const loading = document.getElementById('loading');
            loading.style.display = show ? 'block' : 'none';
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            generateEquationMatrixInputs();
            generateEigenvalueMatrixInputs();
            updateEquationInputs();
            updateEigenvalueInputs();
        });
    </script>
</body>
</html>